package com.ruoyi.prod.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.prod.es.EsProd;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.HighlightQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.ruoyi.prod.mapper.TbProdMapper;
import com.ruoyi.prod.domain.TbProd;
import com.ruoyi.prod.service.ITbProdService;

/**
 * 商品管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-08
 */
@Service
@Slf4j
public class TbProdServiceImpl implements ITbProdService 
{
    @Autowired
    private TbProdMapper tbProdMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 查询商品管理
     * 
     * @param prodId 商品管理主键
     * @return 商品管理
     */
    @Override
    public TbProd selectTbProdByProdId(Integer prodId)
    {
        return tbProdMapper.selectTbProdByProdId(prodId);
    }

    /**
     * 查询商品管理列表
     * 
     * @param tbProd 商品管理
     * @return 商品管理
     */
    @Override
    public List<TbProd> selectTbProdList(TbProd tbProd)
    {
        return tbProdMapper.selectTbProdList(tbProd);
    }

    /**
     * 新增商品管理
     * 
     * @param tbProd 商品管理
     * @return 结果
     */
    @Override
    public int insertTbProd(TbProd tbProd)
    {
        tbProd.setCreateTime(DateUtils.getNowDate());
        return tbProdMapper.insertTbProd(tbProd);
    }

    /**
     * 修改商品管理
     * 
     * @param tbProd 商品管理
     * @return 结果
     */
    @Override
    public int updateTbProd(TbProd tbProd)
    {
        tbProd.setUpdateTime(DateUtils.getNowDate());
        return tbProdMapper.updateTbProd(tbProd);
    }

    /**
     * 批量删除商品管理
     * 
     * @param prodIds 需要删除的商品管理主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdIds(Integer[] prodIds)
    {
        return tbProdMapper.deleteTbProdByProdIds(prodIds);
    }

    /**
     * 删除商品管理信息
     * 
     * @param prodId 商品管理主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdId(Integer prodId)
    {
        return tbProdMapper.deleteTbProdByProdId(prodId);
    }

    @Override
    public TableDataInfo GetPageProd(TbProd tbProd, Integer pageNum, Integer pageSize) {

    log.info("开始es数据查询");
        Integer pageNum1=0;
        if(pageNum>0){
            pageNum1=pageNum-1;
        }
        PageRequest page = PageRequest.of(pageNum1, pageSize);
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);

        boolean exists = indexOps.exists();
        if(!exists){
            //创建索引
            indexOps.create();
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        if(tbProd.getProdName()!=null){
            queryBuilder.must(
                    QueryBuilders.matchQuery("prodName",tbProd.getProdName())
            );
        }
        if(tbProd.getProdSpu()!=null){
            queryBuilder.must(
                    QueryBuilders.matchQuery("prodSpu",tbProd.getProdSpu())
            );

        }
        FieldSortBuilder prodId = SortBuilders.fieldSort("prodId").order(SortOrder.DESC);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder highlightBuilder1 = highlightBuilder.field("prodName").field("prodSpu").preTags("<font color='red'>").postTags("</font>");
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(page).withSorts(prodId).withQuery(queryBuilder).withHighlightBuilder(highlightBuilder1);
        SearchHits<EsProd> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsProd.class);
        List<EsProd> list = new ArrayList<>();
        for (SearchHit<EsProd> esProdSearchHit : search) {
            EsProd content = esProdSearchHit.getContent();
            List<String> prodName = esProdSearchHit.getHighlightField("prodName");
            if(prodName!= null&&prodName.size()>0){
                for (String s : prodName) {
                    content.setProdName(s);
                }
            }
            List<String> prodSpu = esProdSearchHit.getHighlightField("prodSpu");
            if(prodSpu!= null&&prodSpu.size()>0){
                for (String ss : prodSpu) {
                    content.setProdSpu(ss);
                }
            }
            list.add(content);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(search.getTotalHits());
        log.info("es数据查询结束");
        return rspData;
    }


    public AjaxResult syncData(){
        log.info("开始同步数据");
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if(!exists){
            //创建索引
            indexOps.create();
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }
        List<TbProd> tbProds = tbProdMapper.selectTbProdList(null);
        for (TbProd tbProd : tbProds) {
            EsProd esProd = BeanUtil.toBean(tbProd, EsProd.class);
            elasticsearchRestTemplate.save(esProd);
        }
        log.info("同步数据结束");
        return AjaxResult.success();
    }
}
